package com.xwj.rabbitmq.Consumer;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import com.xwj.data.StaticData;
import com.xwj.entity.RaOrder;
import com.xwj.service.Impl.RaOrderServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AddOrderReceive {

    @Autowired
    private RaOrderServiceImpl raOrderService;

    @RabbitHandler
    @RabbitListener(queues = StaticData.AMQP_MQ_QUEUE_TOPIC_ADD_ORDER)
    public void receiveMessage(Message message, Channel channel) {
        try {
            long tag = message.getMessageProperties().getDeliveryTag();
            String msg = new String(message.getBody());
            RaOrder raOrder = JSON.parseObject(msg, new TypeReference<RaOrder>() {
            });
            //手动应答
            if (raOrderService.addOneOrder(raOrder) > 0)
                channel.basicAck(tag, false);
            else
                channel.basicNack(tag, false, false);
        } catch (Exception e) {
            log.info("消费者接收消息异常:", e);
            e.printStackTrace();
        }
    }
}
